package com.example;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.*;

@WebServlet("/example/XmlServlet")
public class XmlServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 解析 XML 请求
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document requestXml = builder.parse(req.getInputStream());

            // 获取用户信息
            String name = requestXml.getElementsByTagName("name").item(0).getTextContent();
            String age = requestXml.getElementsByTagName("age").item(0).getTextContent();

            // 处理业务逻辑（模拟）
            String status = Integer.parseInt(age) > 18 ? "Adult" : "Minor";

            // 构建 XML 响应
            Document responseXml = builder.newDocument();
            Element responseElement = responseXml.createElement("response");
            responseXml.appendChild(responseElement);

            Element userElement = responseXml.createElement("user");
            responseElement.appendChild(userElement);

            Element nameElement = responseXml.createElement("name");
            nameElement.setTextContent(name);
            userElement.appendChild(nameElement);

            Element statusElement = responseXml.createElement("status");
            statusElement.setTextContent(status);
            userElement.appendChild(statusElement);

            // 设置响应头
            resp.setContentType("application/xml");
            resp.setCharacterEncoding("UTF-8");

            // 将 XML 写入响应
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(responseXml);
            PrintWriter writer = resp.getWriter();
            StreamResult result = new StreamResult(writer);
            transformer.transform(source, result);

        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error processing XML");
        }
    }
}